<script type="text/html" id="spec">
    {{#  layui.each(d.spec, function(index, item){ }}
    <div class="spec-item sortable" id="sortable{{index}}" data-index="{{index}}">
        <div class="spec-item-icon">
            <i class="layui-icon layui-icon-more-vertical"></i>
        </div>
        <div class="spec-item-sortable">
            <div class="spec-item-child-title"><span>{{item.title}}</span>
                <i class="layui-icon layui-icon-close close-item" data-id="{{item.id}}"></i>
            </div>
            <div class="spec-content">
                <div class="spec-item-child-lay">
                    {{# layui.each(item.child, function(k, c){ }}
                    <div class="spec-item-child">
                        <span>{{c.title}}</span> <i class="layui-icon layui-icon-close close-child"
                                                    data-id="{{c.id}}"></i>
                    </div>
                    {{# }); }}
                    <div class="layui-form-item">
                        <div class="layui-input-inline layui-input-wrap">
                            <input type="text" autocomplete="off" lay-affix="clear"
                                   class="layui-input attribute" placeholder="填写属性名">
                        </div>
                        <div class="layui-form-mid add-spec-item-child" data-id="{{item.id}}"
                             style="padding: 0!important;">
                            <button type="button" class="layui-btn layui-btn-sm">添加</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    {{#  }); }}
</script>

{foreach name="tape" item="vo"}
<script type="text/html" id="{$vo.field}Tpl">
    {if !empty($vo['type']) && $vo['type'] == 'icon'}
    <div class="tpl-icon openGallery" data-t="1" data-n="{$vo.field}" data-c="1">
        {{# if(d.{$vo.field}){ }}
        <img src="{{d.{$vo.field}}}" class="icon-spec"/>
        {{# }else{ }}
        <i class="layui-icon layui-icon-picture"></i>
        {{# } }}
    </div>
    {else}
    <input type="number" name="{$vo.field}" placeholder="请填写" autocomplete="off" class="layui-input {$vo.field}"
           value="{{d.{$vo.field}}}" style="text-align: center"
           onkeyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'')">
    {/if}
</script>
{/foreach}

<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="vol">批量添加</a>
        <a class="layui-btn layui-btn-xs" lay-event="clear">清空</a>
    </div>
</script>

<script type="text/html" id="specDemo">
    <div class="layui-remove-space">
        <a lay-event="remove">删除</a>
    </div>
</script>
<!-- 隐藏域数据Start -->
<input type="hidden" id="initSpec" value='<?php echo !empty($info) ? $info->spec :"";?>'/>
<input type="hidden" id="initTableSpec" value='<?php echo !empty($info) ? $info->table_spec :"";?>'/>
<input type="hidden" id="tape" value='<?php echo json_encode($tape);?>'/>
<input type="hidden" id="cate1" value='<?php echo !empty($info) ? $info->cate_1 :"";?>'/>
<!-- 隐藏域数据End -->
<script>

    $(function () {
        var a = $, f = layui.form, tpl = layui.laytpl, ly = layui.layer, api = {
                getSpec: '{:url("spec/getSpec")}',
                getProductCate: '{:url("productCate/getCate")}',
                addSpecTpl: '{:url("spec/add")}?tpl=1&backUrl=1'
            },
            initSpec = a('#initSpec').val(),
            initTableSpec = a('#initTableSpec').val(),
            initOk = false,
            initMove = false,
            tape = a('#tape').val(),
            cate1 = a('#cate1').val(),
            spec = initSpec ? JSON.parse(initSpec) : [],
            parseSpec = [],
            box = a(".spec-box"), util = layui.util, t = layui.table,
            ele = layui.element, iconThis = '', iconThisType = 'batch-table';

        /** 规格快拖拽Start **/
        a('.spec-box').disableSelection();
        a('.spec-box').sortable({
            axis: 'y',
            cursor: "move",
            start: function (event, ui) {
                a(ui.item).find('.spec-item-sortable').addClass("box-sortable");
                a(ui.item).parents('.spec-box').addClass('spec-box-sortable')
            },
            stop: function (event, ui) {
                a(ui.item).find('.spec-item-sortable').removeClass("box-sortable");
                a(ui.item).parents('.spec-box').removeClass('spec-box-sortable')
            },
            update: function (event, ui) {
                if (!initMove) {
                    parseSpec = spec;
                    initMove = true;
                }
                notify.warning('变更位置后，需要重新生成商品属性');
                let newIndex = [];
                a('.spec-item').each(function () {
                    newIndex.push(parseInt(a(this).attr('data-index')))
                });
                spec = Object.values(newIndex).map(index => parseSpec[index]);
                layerLoad()
                combination(spec);
                ly.closeAll()
            }
        });
        /** 规格快拖拽End **/

        //初始化规格模板
        getSpecTpl();
        if (cate1) renderCate2(a("#cate_2"), cate1);

        ele.on('tab(brief)', function (data) {
            if (data.index === 1 && initSpec && !initOk) {
                layerLoad()
                renderSpec();
                combination(spec);
                if (initTableSpec) {
                    t.reloadData('spec-table', {
                        data: JSON.parse(initTableSpec)
                    });
                }
                ly.closeAll()
                initOk = true;
            }
        });
        f.on('select(group_cate)', function (data) {
            a('#lay-group-cate1').val(a(data.elem[data.elem.selectedIndex]).attr('data-pid'))
        });
        f.on('radio(spec_open)', function (data) {
            if (data.elem.value === '1') {
                a('.spec-only').show();
                a('.spec-many').hide()
            } else {
                a('.spec-only').hide();
                a('.spec-many').show()
            }
        });

        f.on('select(spec_id)', function (data) {
            if (!data.value) {
                box.html('');
                spec = [];
                return false;
            }
            a.ajax({
                url: api.getSpec,
                type: 'GET',
                async: false,
                data: {id: data.value},
                success: function (data) {
                    tpl(a('#spec').html()).render({spec: data.data.specText}, function (html) {
                        spec = data.data.specText;
                        box.html(html);
                        f.render()
                    });
                }
            })
        });
        f.on('submit(saveProduct)', function (data) {
            var form = f.val('form'), btn = $(this), back_url = btn.attr('data-back-url');
            form.tableSpec = t.getData('spec-table');
            form.spec = spec;
            form.initOk = initOk;
            btn.attr('disabled', true);
            layerLoad()
            a.post("{:url('save')}", form, function (d) {
                if (d.code === 1) {
                    ly.msg(d.msg, {time: 1000}, function () {
                        parent.layer.closeAll();
                        if (back_url) {
                            location.href = back_url;
                        } else {
                            if (parent.$(".layui-table-page").length > 0) {
                                parent.layui.table.reload('form_table', {
                                    page: {
                                        curr: parent.$(".layui-laypage-em").next().text()
                                    },
                                });
                            } else {
                                var w = window.frames.frameElement.id.includes('layui-layer-iframe');
                                w ? parent.location.reload() : location.reload();
                            }
                        }
                    })

                } else {
                    ly.msg(d.msg);
                }
            });
            return false;
        });

        function getSpecTpl() {
            a.get(api.getSpec, {id: '', type: 2}, function (d) {
                let html = '<option value="">选择规格模板</option>';
                d.data.forEach(function (v, i) {
                    html += '<option value="' + v.id + '">' + v.title + '</option>';
                });
                a('#spec_id').html(html);
                f.render();
            });

        }

        util.on('lay-on', {
            addSpecTpl: function () {
                var w = a(window).width(), ew = w < 1200 ? '90%' : '70%';
                ly.open({
                    type: 2,
                    area: [ew, '60%'],
                    content: api.addSpecTpl,
                    fixed: false,
                    maxmin: true,
                    shadeClose: true,
                    title: '添加规格模板',
                    end: function () {
                        getSpecTpl();
                    }
                });
            },
            generate: function () {
                if (spec.length <= 0) {
                    ly.msg('请选择规格模板或添加新规格后再生成');
                    return false;
                }
                layerLoad()
                const oldTableData = t.getData('spec-table');
                combination(spec);
                const newTableData = t.getData('spec-table');

                oldTableData.forEach(function (v, i) {
                    const keys = Object.keys(v), values = Object.values(v), newArr = [];
                    keys.forEach(function (v, i) {
                        if (v.split('$$').length > 1) {
                            newArr.push(values[i]);
                        }
                    })
                    oldTableData[i].extract = newArr.join(',');
                })

                newTableData.forEach(function (v, i) {
                    let keys = Object.keys(v), values = Object.values(v), newArr = [];
                    keys.forEach(function (v, i) {
                        if (v.split('$$').length > 1) {
                            newArr.push(values[i]);
                        }
                    })

                    function getSame(arr, extract) {
                        let same = '';
                        arr.forEach(function (item, index) {
                            if (item.extract === extract) {
                                same = item;
                            }
                        });
                        return same;
                    }

                    var data = getSame(oldTableData, newArr.join(','));
                    if (data) {
                        newTableData[i] = data;
                    }
                });

                t.reloadData('spec-table', {
                    data: newTableData
                });
                a('.generate').show();
                ly.closeAll();
            },
            add: function () {
                a('.add-spec-item').css('display', 'block');
                a(this).hide();
                a('.generate-btn').hide();
            },
            clare: function () {
                a('.add-spec-item').hide();
                a('.add-spec-btn').show();
                a('.generate-btn').show();
                a('#spec-title').val('');
                a('#spec-val').val('');
            },
            addOk: function () {
                let title = a('#spec-title').val(), val = a('#spec-val').val(), open = true;
                if (title && val) {
                    spec.forEach(function (v, i) {
                        if (v.title === title) {
                            open = false;
                        }
                    })
                    if (open) {
                        spec.push({
                            id: a.now(),
                            title: title,
                            child: [
                                {id: a.now() + 1, title: val},
                            ]
                        });
                        renderSpec();
                        a('.add-spec-item').hide();
                        a('.add-spec-btn').show();
                        a('.generate-btn').show();
                        a('#spec-title').val('');
                        a('#spec-val').val('');
                    } else {
                        ly.msg('规格名已存在，请修改或者完善对应规格属性');
                    }

                } else {
                    ly.msg('请填写完整规格');
                }
            },
        });

        box.on('click', '.close-item', function () {
            removeSpec(parseInt(a(this).attr('data-id')), 1);
        }).on('click', '.close-child', function () {
            removeSpec(parseInt(a(this).attr('data-id')), 2);
        }).on('click', '.add-spec-item-child', function () {
            const text = a(this).parent().find('.attribute').val(), id = parseInt(a(this).attr('data-id'));
            if (text) {
                spec.forEach(function (item, index) {
                    if (parseInt(item.id) === id) {
                        let open = true;
                        item.child.forEach(function (v, i) {
                            if (v.title === a.trim(text)) {
                                open = false;
                            }
                        })
                        if (open) {
                            item.child.push(
                                {id: a.now(), title: a.trim(text)}
                            );
                        } else {
                            ly.msg('属性已存在');
                        }

                    }
                });
                renderSpec();
            } else {
                ly.msg('请添加属性');
            }
        });

        function renderSpec() {
            tpl(a('#spec').html()).render({spec: spec}, function (html) {
                box.html(html);
                f.render()
            });
        }

        function removeSpec(id, type) {
            if (type === 1) {
                spec.forEach(function (item, index) {
                    if (parseInt(item.id) === id) {
                        spec.splice(index, 1);
                        return false;
                    }
                });
            } else {
                spec.forEach(function (i, k) {
                    i.child.forEach(function (item, index) {
                        if (parseInt(item.id) === id) {
                            i.child.splice(index, 1);
                            return false;
                        }
                    });
                });

            }
            renderSpec();
        }

        function combination(spec) {
            combineTable(combineSpecs(spec), spec, tape ? JSON.parse(tape) : [])
        }

        //笛卡尔乘积组合规格项
        function combineSpecs(specs, fs = true) {
            if (fs) {
                var newSpec = [];
                specs.forEach(function (i, k) {
                    let data = {name: i.title, value: []}
                    i.child.forEach(function (item, index) {
                        data.value.push(item.title)
                    });
                    if (data.value.length > 0) {
                        newSpec.push(data)
                    }
                });
                specs = newSpec;
            }
            if (specs.length === 0) {
                return [[]];
            } else {
                const [head, ...tail] = specs;
                const rest = combineSpecs(tail, false);
                const pairs = head.value.map(value => rest.map(r => [value, ...r]));
                return [].concat(...pairs);
            }
        }

        // 生成table表格
        function combineTable(s, n, o) {
            var html = '<table lay-filter="spec-table">', batchHtml = '<table lay-filter="batch-table">';
            html += '<thead><tr>';
            batchHtml += '<thead><tr>';
            n.forEach(function (i, k) {
                if (i.child.length > 0) {
                    html += '<th lay-data="{field:\'spec$$Title_' + i.id + '\',align:\'center\'}">' + i.title + '</th>';
                }
            });
            o.forEach(function (i, k) {
                html += '<th lay-data="{field:\'' + i.field + '\',templet: \'#' + i.field + 'Tpl\',align:\'center\'}">' + i.title + '</th>';
                batchHtml += '<th lay-data="{field:\'' + i.field + '\',templet: \'#' + i.field + 'Tpl\',align:\'center\'}">' + i.title + '</th>';
            });
            html += '<th lay-data="{toolbar: \'#specDemo\',align:\'center\',width:90}">操作</th>';
            html += '</tr></thead>';
            html += '<tbody>';

            batchHtml += '<th lay-data="{toolbar: \'#barDemo\',align:\'center\'}">操作</th>';
            batchHtml += '</tr></thead>';
            batchHtml += '<tbody>';

            s.forEach(function (d, k) {
                html += '<tr>';
                for (var i = 0; i < d.length; i++) {
                    html += '<td>' + d[i] + '</td>';
                }
                o.forEach(function (i, k) {
                    html += '<td></td>';
                });
                html += '</tr>';
            });
            html += '</tbody>';
            html += '</table>';

            a('.spec-table').html(html);

            t.init('spec-table', {
                id: 'spec-table',
                size: 'sm',
                done: function () {
                    var options = this;
                    t.getRowData = function (elem) {
                        var index = $(elem).closest('tr').data('index');
                        return t.cache[options.id][index] || {};
                    };

                    t.on('tool(spec-table)', function (obj) {
                        if (obj.event === 'remove') {
                            obj.del();
                        }
                    });

                }
            });

            '<?php foreach($tape as $vo){?>'
            a('.spec-table').on('input', '.{$vo.field}', function (e) {
                var data = t.getRowData(a(this));
                data.{$vo.field} = a(this).val();
            });

            a('.batch-table').on('input', '.{$vo.field}', function (e) {
                var data = t.getRowDataBatch(a(this));
                data.{$vo.field} = a(this).val();
            })
            '<?php }?>'

            batchHtml += '<tr>';
            o.forEach(function (i, k) {
                batchHtml += '<td></td>';
            });
            batchHtml += '</tr></tbody></table>';

            a('.batch-table').html(batchHtml);
            t.init('batch-table', {
                size: 'sm',
                id: 'batch-table',
                done: function () {
                    var options = this;
                    t.getRowDataBatch = function (elem) {
                        var index = $(elem).closest('tr').data('index');
                        return t.cache[options.id][index] || {};
                    };
                    t.on('tool(batch-table)', function (obj) {
                        var bd = t.getData('batch-table'), td = t.getData('spec-table'), keys = Object.keys(bd[0]),
                            val = Object.values(bd[0]);
                        td.forEach(function (item, index) {
                            for (let i = 0; i < keys.length; i++) {
                                if (Object.keys(item).includes(keys[i])) {
                                    td[index][keys[i]] = obj.event === 'vol' ? val[i] : '';
                                    obj.event === 'vol' ? a('.spec-table').find('.' + keys[i]).val(val[t]) : a('.' + keys[i]).val('');
                                }
                            }
                        })
                        t.reloadData('spec-table', {
                            data: td
                        });
                        if (obj.event === 'clear') {
                            a('.batch-table').find('.openGallery').html('<i class="layui-icon layui-icon-picture"></i>');
                            var thisCache = t.cache['batch-table'] || {};
                            thisCache[0].icon = '';

                        }
                    });

                }
            });
            f.render()
        }

        f.on('select(cate_1)', function (data) {
            if(data.value == 1){
                $("#levelshow2").show();
            }else{
                $("#levelshow2").hide();
            }
            if(data.value == 2 || data.value == 7){
                $("#bonusshow").hide();
            }else{
                $("#bonusshow").show();
                if(data.value == 1){
                    $("#bonus_text").text('缔造积分');
                }else{
                    $("#bonus_text").text('燃料积分')
                }
            }
            if (data.value) {
                renderCate2(a("#cate_2"), data.value);
            } else {
                a("#cate_2").html('<option value="">请选择</option>');
                f.render();
            }
        });

        function renderCate2(obj, id) {
            a.get(api.getProductCate, {id: id}, function (data) {
                var options = '<option value="">请选择</option>';
                a.each(data, function (i) {
                    var selected = obj.attr('data-id') == data[i]['id'] ? 'selected' : '';
                    options += '<option value="' + data[i]['id'] + '" ' + selected + '>' + data[i]['title'] + '</option>';
                })
                obj.html(options);
                f.render();
            })
        }


        a('.batch-table').on('click', '.openGallery', function () {
            //暴露当前this在外
            iconThis = a(this);
            iconThisType = 'batch-table';
            var c = a(this).attr('data-c'), n = a(this).attr('data-n'), t = a(this).attr('data-t'),
                v = iconThis.find('.icon-spec').attr('src'), h = 650,
                w = window.frames.frameElement.id.includes('layui-layer-iframe'),
                l = w ? parent.layer : layer;
            if (a(window).height() < h) h = ($(window).height() - 20);
            v = typeof (v) !== 'undefined' ? v : '';

            l.open({
                type: 2,
                area: ['1000px', h + 'px'],
                fix: false,
                maxmin: true,
                shadeClose: true,
                shade: 0.4,
                anim: 2,
                title: '选择图片',
                content: '/' + a("#admin_map").val() + '/gallery/open.html?t=' + t + '&c=' + c + "&n=" + n + '&v=' + v + '&spec=1',
            });

        })

        a('.spec-table').on('click', '.openGallery', function () {
            //暴露当前this在外
            iconThis = a(this);
            iconThisType = 'spec-table';
            var c = a(this).attr('data-c'), n = a(this).attr('data-n'), t = a(this).attr('data-t'),
                v = iconThis.find('.icon-spec').attr('src'), h = 650,
                w = window.frames.frameElement.id.includes('layui-layer-iframe'),
                l = w ? parent.layer : layer;
            if (a(window).height() < h) h = ($(window).height() - 20);
            v = typeof (v) !== 'undefined' ? v : '';

            l.open({
                type: 2,
                area: ['1000px', h + 'px'],
                fix: false,
                maxmin: true,
                shadeClose: true,
                shade: 0.4,
                anim: 2,
                title: '选择图片',
                content: '/' + a("#admin_map").val() + '/gallery/open.html?t=' + t + '&c=' + c + "&n=" + n + '&v=' + v + '&spec=1',
            });

        })

        renderGallerySpec = function (i, u, n, ty) {

            iconThis.html(u.length > 0 ? '<img src="' + u[0] + '" class="icon-spec"/>' : '<i class="layui-icon layui-icon-picture"></i>');
            var w = window.frames.frameElement.id.includes('layui-layer-iframe'),
                l = w ? parent.layer : layer;
            l.close(l.index)
            var thisCache = t.cache[iconThisType] || {};

            thisCache[0].icon = u.length > 0 ? u[0] : '';

        }

    });
</script>